import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { fetchCityTreeList } from '@/business/services/common/common';
import { handleCityTree } from '@/utils/format';

/**
 * @description 地区选择树状列表
 * @author Shawn
 */

type RequestFunction = () => Promise<void>;

type State = {
  // 地区选择树状列表
  cityTreeList: any;
};

type Actions = {
  // 获取地区选择树状列表
  getCityTreeList: RequestFunction;
};

const initialState: State = {
  cityTreeList: [],
};

export const cityTreeListStore = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取地区选择树状列表
     */
    getCityTreeList: async () => {
      const cityTreeList = get().cityTreeList;
      if (cityTreeList && cityTreeList.length > 0) return;
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const res = await fetchCityTreeList({});
        const rawCitys = res.data;
        handleCityTree(rawCitys);
        set((state) => {
          state.cityTreeList = rawCitys;
        });
      } catch (error) {
        console.log('获取地区选择树状列表失败', error);
      } finally {
        Taro.hideLoading();
      }
    },
  })),
);
